<?php


namespace App\Api\Controllers\YSEPay;


use App\Api\Controllers\YSEPay\YSEPayUtil\RSA256Util;
use App\Api\Controllers\YSEPay\YSEPayUtil\SignUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class NotifyController
{

    private $privateKeyPath = 'client.pfx';//商户端的私钥证书 (RSA加密)
    private $publicKeyPath = 'service.cer';//银盛端公钥证书 (RSA加密)

    private function request_by_curl($remote_server, $post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        // curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    //推送消息
    private function send($message)
    {
        try {
            $webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=5a296931-47dc-40da-8819-d31ea40af930";
            $data = [
                'msgtype' => 'markdown',
                'markdown' => [
                    'content' => $message
                ]
            ];
            $data_string = json_encode($data);
            $result = $this->request_by_curl($webhook, $data_string);
            $result = json_decode($result, true);
            if ($result === null && json_last_error() !== JSON_ERROR_NONE) {
                throw new \Exception('推送返回数据格式有误');
                return false;
            }
            if ($result['errcode'] != 0) {
                throw new \Exception($result['errmsg']);
                return false;
            }
        } catch (\Exception $e) {

        }
        return true;
    }

    public function __construct()
    {
        $this->privateKeyPath = app_path('Api/Controllers/YSEPay/YSEPayUtil/' . $this->privateKeyPath);
        $this->publicKeyPath = app_path('Api/Controllers/YSEPay/YSEPayUtil/' . $this->publicKeyPath);
    }

    //进件回调
    public function notify(Request $request)
    {
        $current_time = time();
        $result = $request->post();
        error_log(date('Y-m-d H:i:s')." 【银盛进件返回】： ".json_encode($result)."\n\n", 3, "/tmp/". 'yc-add-mch'.date('Ymd').".log");
        try {
            if (!RSA256Util::verifySign($this->publicKeyPath, $result['sign'], SignUtil::map2SortedSignStr($result))) {
                throw new \Exception('数据解析异常，请联系管理员1');
            }
            $result['bizContent'] = json_decode($result['bizContent'], true);
            if ($result['bizContent'] === null && json_last_error() !== JSON_ERROR_NONE) {
                throw new \Exception('数据解析异常，请联系管理员2');
            }
            $bizContent = $result['bizContent'];
            switch (intval($bizContent['notifyType'])) {
                case 1://通知类型 固定为1（客户进件异步通知）
                    $cust = $bizContent['cust'];
                    DB::table('ysepay_stores')->where(['sys_flow_id' => $cust['sysFlowId']])->update([
                        'sys_flow_id' => $cust['sysFlowId'],
                        'cust_id' => $cust['custId'],
                        'sys_flow_status' => $bizContent['status'],
                        'update_time' => $current_time,
                    ]);
                    break;
                case 2://通知类型 固定为2（权限与费率配置异步通知）
                    $auth = $bizContent['auth'];
                    DB::table('ysepay_stores')->where(['cust_id' => $auth['custId']])->update([
                        'auth_id' => $auth['authId'],
                        'merc_id' => $auth['mercId'],
                        'sign_status' => $bizContent['status'],
                        'update_time' => $current_time,
                    ]);
                    break;
                case 6://通知类型 固定为6（报备异步通知）
                    $current = time();
                    $report = $bizContent['report'];
                    if (isset($report['mercId']) && !empty($report['mercId'])) {
                        $authId = $report['authId'];
                        $mercId = $report['mercId'];
                        $ysepay_stores = DB::table('ysepay_stores')->where(['auth_id' => $authId])->first();
                        if (!$ysepay_stores && !empty($ysepay_stores->store_id)) {
                            $this->send("银盛报备回调查询\n>" . implode("\n>", [
                                    "不存在编号: <font color=\"info\">" . $report['authId'] . "</font>",
                                ]));
                        } else {
                            DB::table('store_pay_ways')
                                ->where(['store_id' => $ysepay_stores->store_id, 'company' => 'yinsheng'])
                                ->update([
                                    'status' => 1,
                                    'status_desc' => '开通成功',
                                    'created_at' => date('Y-m-d H:i:s', $current_time),
                                    'updated_at' => date('Y-m-d H:i:s', $current_time),
                                ]);
                            DB::table('ysepay_stores')->where(['auth_id' => $authId])->update([
                                'merc_id' => $mercId,
                                'sign_status' => '00',
                            ]);
                            DB::table('yinsheng_stores')->insert([
                                'config_id' => '1234',
                                'store_id' => $ysepay_stores->store_id,
                                'partner_id' => '826361673720106',
                                'seller_id' => $mercId,
                                'seller_name' => '',
                                'business_code' => '00510030',
                                'status' => 1,
                                'created_at' => date('Y-m-d H:i:s', $current_time),
                                'updated_at' => date('Y-m-d H:i:s', $current_time)
                            ]);
                        }
                    }
                    $this->send("银盛报备回调信息\n>" . implode("\n>", [
                            "回调数据: <font color=\"info\">" . json_encode($result, true) . "</font>",
                        ]));
                    break;
                default:
                    throw new \Exception('未定义的回调');
            }
            return 'success';
        } catch (\Exception $e) {
            //var_dump($e->getMessage());
            Log::error($e->getMessage(), $result);
             //$this->send("银盛回调报错\n>" . implode("\n>", [
             //        "回调数据: <font color=\"info\">" . json_encode($result, true) . "</font>",
              //      "错误内容: <font color=\"warning\">" . $e->getMessage() . "</font>"
             //  ]));
            return 'error';
        }

    }

    //支付回调
    public function payNotify(Request $request)
    {
        $result = $request->post();
        try {
            /*if (!RSA256Util::verifySign($this->publicKeyPath, $result['sign'], SignUtil::map2SortedSignStr($result))) {
                throw new \Exception('验签失败，请联系管理员');
            }*/
            $result['alipay_trx_resp_coupon_info'] = json_decode($result['alipay_trx_resp_coupon_info'], true);
            if ($result['alipay_trx_resp_coupon_info'] === null && json_last_error() !== JSON_ERROR_NONE) {
                throw new \Exception('数据解析异常，请联系管理员');
            }
            switch ($result['notify_type']) {
                case 'directpay.status.sync':
                    if ($result['trade_status'] == 'TRADE_SUCCESS') {
                        DB::table('orders')->where('out_trade_no', $result['out_trade_no'])->update([
                            'status' => 1,//支付成功
                            'pay_status' => 1,//支付成功
                            'pay_status_desc' => "支付成功",
                            'trade_no' => $result['trade_no'],//支付成功
                            'buyer_pay_amount' => number_format($result['alipay_trx_resp_coupon_info']['buyer_pay_amount'], 2, '.', ''),
                            'discount_amount' => number_format($result['total_discount'], 2, '.', ''),
                            'pay_time' => $result['notify_time'],
                            'updated_at' => $result['notify_time'],
                        ]);
                    } else {
                        throw new \Exception('回调订单状态非支付成功');
                    }
                    break;
                default:
                    throw new \Exception('未定义的回调');
            }
            return 'success';
        } catch (\Exception $e) {
            Log::error($e->getMessage(), $result);
            $this->send("银盛回调报错\n>" . implode("\n>", [
                    "回调数据: <font color=\"info\">" . json_encode(['data' => $result], true) . "</font>",
                    "错误内容: <font color=\"warning\">" . $e->getMessage() . "</font>"
                ]));
            return 'success';
        }
    }


    //退款回调
    public function refundNotify()
    {
        Log::info('回调成功');
        return 'success';
    }

}